# -*- coding: utf-8 -*-

import binascii
from hashlib import md5, sha1
import redis
import simplejson as json
from Crypto.Cipher import AES

from random import choice
from string import ascii_letters, digits

def encrypt(api_key, api_secret_key, nonce, raw):
    key = md5(api_key + nonce).hexdigest()[::-2]
    iv = md5(nonce + api_secret_key).hexdigest()[::-2]
    print key, iv
    raw += (16 - len(raw) % 16) * '\0'
    generator = AES.new(key, AES.MODE_CBC, IV=iv)
    return binascii.b2a_hex(generator.encrypt(raw))


def decrypt(api_key, api_secret_key, nonce, enc):
    key = md5(api_key + nonce).hexdigest()[::-2]
    iv = md5(nonce + api_secret_key).hexdigest()[::-2]
    enc = binascii.unhexlify(enc)
    cipher = AES.new(key, AES.MODE_CBC, iv)
    temp =cipher.decrypt(enc).decode('utf-8').rstrip("\0")
    try:
        return 0, json.loads (temp)
    except (SyntaxError, NameError), e:
        return -40008, None

def get_sha1(*args):
    try:
        sort_list = map(lambda x: str(x), args)
        sort_list.sort()
        sha = sha1()
        sha.update("".join(sort_list))

        return sha.hexdigest().upper()
    except Exception, e:
        return None

def random_str(length=8):
    char = ascii_letters + digits
    return "".join(choice(char) for _ in range(length))


def random_num(length=8):
    char = digits
    return "".join(choice(char) for _ in range(length))


def random_alpha(length=6):
    char = ascii_letters
    return "".join(choice(char) for _ in range(length))


def build_json(errcode, errmsg, data=None):
    ret = {
        'errcode': errcode,
        'errmsg': errmsg,
    }
    if data:
        ret['data'] = data

    return json.dumps(ret)

















